import json
import os
import time
import traceback
import urllib.request
file_path = "/home/forlinx/klipper/print_states.json"


def get_status():
    # 目标URL
    try:
        url = 'http://localhost/printer/objects/query?power_resume_status&print_stats'
        # 打开URL
        response = urllib.request.urlopen(url)
        # 读取数据
        data = response.read()
        data_decoded = data.decode('utf-8')
        state = json.loads(data_decoded)
        return state['result']['status']['power_resume_status'], state['result']['status']['print_stats']
    except Exception as e:
        s = traceback.format_exc()
        print(s)
        return None, None


def save_data(power_resume_status):
    with open(file_path, 'w') as f:
        json.dump(power_resume_status, f)


def process():
    time.sleep(10)
    while True:
        time.sleep(0.1)
        try:
            power_resume_status, print_stats = get_status()
            # print(power_resume_status)
            if print_stats['state'] == 'printing':
                if power_resume_status:
                    save_data(power_resume_status)
            if print_stats['state'] == 'complete':
                if os.path.exists(file_path):
                    os.remove(file_path)
        except Exception as e:
            time.sleep(4)
            s = traceback.format_exc()
            print(s)
            # break


process()
